package crmdna.user;

import java.util.List;

import javax.inject.Named;

import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.config.ApiMethod.HttpMethod;
import com.google.appengine.api.users.User;

import crmdna.common.APIResponse;
import crmdna.common.APIResponse.Status;
import crmdna.common.Utils;
import crmdna.user.User.Action;
import crmdna.user.User.ResourceType;
import crmdna.user.UserCore.UserProp;

@Api(name = "user")
public class UserApi {
	@ApiMethod(path = "create", httpMethod = HttpMethod.POST)
	public APIResponse create(@Named("client") String client,
			@Named("email") String email, @Named("group_id") long groupId,
			User user) {

		try {
			UserProp prop = crmdna.user.User.create(client, email, groupId,
					Utils.getLoginEmail(user));

			return new APIResponse(Status.SUCCESS, prop);

		} catch (Exception ex) {
			return new APIResponse(ex);
		}
	}

	@ApiMethod(path = "addOrDeletePrivilege", httpMethod = HttpMethod.POST)
	public APIResponse addOrDeletePrivilege(@Named("client") String client,
			@Named("email") String email,
			@Named("resource_type") ResourceType resourceType,
			@Named("resource_id") long resourceId,
			@Named("action") Action action, @Named("add") Boolean add, User user) {

		try {

			UserProp prop = crmdna.user.User.addOrDeletePrivilege(client,
					email, resourceType, resourceId, action, add,
					Utils.getLoginEmail(user));

			return new APIResponse(Status.SUCCESS, prop);

		} catch (Exception ex) {
			return new APIResponse(ex);
		}
	}

	@ApiMethod(path = "getAll", httpMethod = HttpMethod.GET)
	public APIResponse getAll(@Named("client") String client) {

		try {
			List<UserProp> props = crmdna.user.User.getAll(client);

			return new APIResponse(Status.SUCCESS, props);

		} catch (Exception ex) {
			return new APIResponse(ex);
		}
	}

	@ApiMethod(path = "getLoggedInUser", httpMethod = HttpMethod.GET)
	public APIResponse getLoggedInUser(User user) {

		try {
			String result = Utils.getLoginEmail(user);

			if (null == result)
				result = "not logged in";

			return new APIResponse(Status.SUCCESS, result);

		} catch (Exception ex) {
			return new APIResponse(ex);
		}
	}

	@ApiMethod(path = "clonePrivileges", httpMethod = HttpMethod.POST)
	public APIResponse clonePrivileges(@Named("client") String client,
			@Named("sourceEmail") String sourceEmail,
			@Named("targetEmail") String targetEmail, User user) {

		try {
			crmdna.user.User.clonePrivileges(client, sourceEmail, targetEmail,
					Utils.getLoginEmail(user));

			UserProp afterCloning = crmdna.user.User.get(client, targetEmail)
					.toProp();

			return new APIResponse(Status.SUCCESS, afterCloning);

		} catch (Exception ex) {
			return new APIResponse(ex);
		}
	}
}
